package com.api.demo.service.impl;

import com.api.demo.dto.CommentRequest;
import com.api.demo.entity.Comment;
import com.api.demo.entity.CommentLike;
import com.api.demo.entity.Content;
import com.api.demo.entity.Like;
import com.api.demo.mapper.CommentLikeMapper;
import com.api.demo.mapper.CommentMapper;
import com.api.demo.service.CommentService;
import com.api.demo.service.ContentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private ContentService contentService;

    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Override
    @Transactional
    public Comment createComment(Long contentId, CommentRequest request, Long userId) {
        // 检查内容是否存在
        Content content = contentService.getContentDetail(contentId);

        Comment comment = new Comment();
        comment.setContentId(contentId);
        comment.setUserId(userId);
        comment.setContent(request.getContent());
        comment.setLikeCount(0);
        comment.setStatus(0);
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());

        save(comment);

        // 更新内容的评论数
        content.setCommentCount(content.getCommentCount() + 1);
        contentService.updateById(content);

        return comment;
    }

    @Override
    @Transactional
    public Comment replyComment(Long contentId, Long commentId, CommentRequest request, Long userId) {
        // 检查内容是否存在
        Content content = contentService.getContentDetail(contentId);

        // 检查父评论是否存在
        Comment parentComment = getById(commentId);
        if (parentComment == null || parentComment.getStatus() == 1) {
            throw new IllegalArgumentException("评论不存在");
        }
        if (!parentComment.getContentId().equals(contentId)) {
            throw new IllegalArgumentException("评论不属于该内容");
        }

        Comment comment = new Comment();
        comment.setContentId(contentId);
        comment.setUserId(userId);
        comment.setParentId(commentId);
        comment.setContent(request.getContent());
        comment.setLikeCount(0);
        comment.setStatus(0);
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());

        save(comment);

        // 更新内容的评论数
        content.setCommentCount(content.getCommentCount() + 1);
        contentService.updateById(content);

        return comment;
    }

    @Override
    public IPage<Comment> getCommentList(Long contentId, Page<Comment> page, Long UserId) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId)
                .eq("status", 0)
                .orderByDesc("create_time");

        IPage<Comment> commentPage = page(page, queryWrapper);

        Set<Long> commentIds = commentPage.getRecords().stream()
                .map(Comment::getId)
                .collect(Collectors.toSet());

        // 4. 批量查询当前用户对这些评论的点赞状态
        Map<Long, Boolean> likeStatusMap = getLikeStatusMap(UserId, commentIds);

        // 5. 设置每个评论的点赞状态
        commentPage.getRecords().forEach(comment -> {
            comment.setIsLiked(likeStatusMap.getOrDefault(comment.getId(), false));
        });
        return commentPage;
    }

    @Override
    @Transactional
    public void likeComment(Long commentId, Long userId) {
        // 检查评论是否存在
        Comment comment = getById(commentId);
        if (comment == null || comment.getStatus() == 1) {
            throw new IllegalArgumentException("评论不存在");
        }

        // 检查是否已经点赞
        QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id", commentId)
                .eq("user_id", userId);
        if (commentLikeMapper.selectCount(queryWrapper) > 0) {
            return; // 已经点赞过了，直接返回
        }

        // 创建点赞记录
        CommentLike commentLike = new CommentLike();
        commentLike.setCommentId(commentId);
        commentLike.setUserId(userId);
        commentLike.setCreateTime(LocalDateTime.now());
        commentLikeMapper.insert(commentLike);

        // 更新评论的点赞数
        comment.setLikeCount(comment.getLikeCount() + 1);
        updateById(comment);
    }

    @Override
    @Transactional
    public void unlikeComment(Long commentId, Long userId) {
        // 检查评论是否存在
        Comment comment = getById(commentId);
        if (comment == null || comment.getStatus() == 1) {
            throw new IllegalArgumentException("评论不存在");
        }

        // 删除点赞记录
        QueryWrapper<CommentLike> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_id", commentId)
                .eq("user_id", userId);
        if (commentLikeMapper.delete(queryWrapper) > 0) {
            // 只有成功删除点赞记录时才减少点赞数
            comment.setLikeCount(comment.getLikeCount() - 1);
            updateById(comment);
        }
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        Comment comment = getById(commentId);
        if (comment == null || comment.getStatus() == 1) {
            throw new IllegalArgumentException("评论不存在");
        }
        if (!comment.getUserId().equals(userId)) {
            throw new IllegalArgumentException("无权删除该评论");
        }

        // 软删除评论
        comment.setStatus(1);
        comment.setUpdateTime(LocalDateTime.now());
        updateById(comment);

        // 更新内容的评论数
        Content content = contentService.getById(comment.getContentId());
        content.setCommentCount(content.getCommentCount() - 1);
        contentService.updateById(content);
    }

    private Map<Long, Boolean> getLikeStatusMap(Long userId, Set<Long> commentIds) {
        if (commentIds.isEmpty()) {
            return Collections.emptyMap();
        }

        // 构建查询条件
        QueryWrapper<CommentLike> query = new QueryWrapper<>();
        query.select("comment_id") // 使用正确的字段名
                .eq("user_id", userId)
                .in("comment_id", commentIds); // 使用正确的字段名

        // 正确使用 Mapper 实例
        List<CommentLike> likes = commentLikeMapper.selectList(query);

        // 使用正确的 getter 方法
        Set<Long> likedCommentIds = likes.stream()
                .map(CommentLike::getCommentId) // 使用 getCommentId()
                .collect(Collectors.toSet());

        // 创建状态映射
        return commentIds.stream()
                .collect(Collectors.toMap(
                        id -> id,
                        likedCommentIds::contains));
    }
}